<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="维修单号" prop="code">
        <el-input v-model="formData.code" disabled />
      </el-form-item>

      <el-form-item label="故障分类" prop="faultId">
        <el-select v-model="formData.faultId" filterable clearable placeholder="请选择故障分类" style="width: 100%;"
          :disabled="formType === 'update'">
          <el-option v-for="cat in repaircategories" :key="cat.id" :label="cat.name" :value="cat.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="模具" prop="accountId">
        <el-select v-model="formData.accountId" filterable clearable placeholder="请选择模具" style="width: 100%;"
          :disabled="formType === 'update'">
          <el-option v-for="account in accountList" :key="account.id" :label="account.code + '(' + account.name + ')'"
            :value="account.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="故障发生时间" prop="faultTime">
        <el-date-picker v-model="formData.faultTime" type="date" value-format="x" placeholder="选择故障时间" />
      </el-form-item>
      <!--       <el-form-item label="申请人ID" prop="applicantId">
        <el-select v-model="formData.applicantId" placeholder="请选择申请人ID">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="申请人" prop="applicantId">
        <el-select v-model="formData.applicantId" filterable clearable placeholder="申请人" style="width: 100%;">
          <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="所属部门" prop="departId">
        <el-tree-select v-model="formData.departId" :data="deptTree" :props="defaultProps" check-strictly filterable
          clearable default-expand-all placeholder="请选择申请部门" value-key="id" />
      </el-form-item>

      <el-form-item label="紧急程度" prop="urgencyLevel">
        <el-select v-model="formData.urgencyLevel" placeholder="请选择紧急程度">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_REPAIR_URGENCY_LEVEL)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="维修方式" prop="repairMethod">
        <el-select v-model="formData.repairMethod" placeholder="请输入维修方式">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_REPAIR_METHOD)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="故障描述" prop="faultDescription">
        <Editor v-model="formData.faultDescription" height="150px" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { watch } from 'vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { RepairAccountApi, RepairAccount } from '@/api/mold/repairaccount'
import { RepairFaultCategoryApi, RepairFaultCategory } from '@/api/mold/repairfaultcategory'
import { AccountApi, Account } from '@/api/mold/account'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'
import { getUserProfile } from '@/api/system/user/profile'

/** 模具维修申请 表单 */
defineOptions({ name: 'RepairAccountForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  accountId: undefined,
  faultId: undefined,
  applicantId: undefined,
  departId: undefined as number | undefined, // 明确类型
  urgencyLevel: undefined,
  faultTime: Date.now(),
  applicationTime: undefined,
  faultDescription: undefined,
  repairMethod: 1,
  status: undefined,
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  accountId: [{ required: true, message: '模具台账ID不能为空', trigger: 'change' }],
  faultId: [{ required: true, message: '故障分类Id不能为空', trigger: 'change' }],
  applicantId: [{ required: true, message: '申请人ID不能为空', trigger: 'change' }],
  departId: [{ required: true, message: '申请部门不能为空', trigger: 'change' }],
  urgencyLevel: [{ required: true, message: '紧急程度不能为空', trigger: 'change' }],
  faultTime: [{ required: true, message: '故障时间不能为空', trigger: 'blur' }],
  applicationTime: [{ required: true, message: '申请时间不能为空', trigger: 'blur' }],
  repairMethod: [{ required: true, message: '维修方式不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const repaircategories = ref()
const accountList = ref()
const userList = ref<UserVO[]>([])
const deptTree = ref() // 树形结构

// 获取当前用户信息
const currentUser = ref<any>(null)

/** 获得部门树 */
const getDeptTree = async () => {
  deptTree.value = []
  let parentId = 115
  const data = await DeptApi.getDeptsById(parentId)
  let dept: Tree = { id: parentId, name: '阿能集团', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}

const getUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}


/** 获得模具列表 */
const getAccountList = async () => {
  accountList.value = []
  const data = await AccountApi.getAccountAll()
  accountList.value = data
  console.log(accountList.value)
}

const getRepaircategories = async () => {
  repaircategories.value = []
  const data = await RepairFaultCategoryApi.getRepairFaultCategoryAll()
  repaircategories.value = handleTree(data)
}

/** 设置默认值 */
const setDefaultValues = async () => {
  if (formType.value === 'create') {
    const user = currentUser.value || await getCurrentUser()
    if (user) {
      // 使用 nextTick 确保在 DOM 更新后设置值
      await nextTick()
      formData.value.applicantId = user.id
      formData.value.departId = user.dept?.id
      formData.value.faultTime = Date.now()

      // 如果需要，可以手动触发表单验证更新
      if (formRef.value) {
        formRef.value.clearValidate(['applicantId', 'departId'])
      }
    }
  }
}


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  // 先获取当前用户信息
  await getCurrentUser()
  
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  
  // 重置表单
  resetForm()
  
  // 加载必要的数据
  await Promise.all([
    getRepaircategories(),
    getAccountList(),
    getUserList(),
    getDeptTree()
  ])
  
  // 设置默认值
  await setDefaultValues()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RepairAccountApi.getRepairAccount(id)
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RepairAccount
    if (formType.value === 'create') {
      await RepairAccountApi.createRepairAccount(data)
      message.success(t('common.createSuccess'))
    } else {
      await RepairAccountApi.updateRepairAccount(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    accountId: undefined,
    faultId: undefined,
    applicantId: undefined,
    departId: undefined,
    urgencyLevel: undefined,
    faultTime: Date.now(),
    applicationTime: undefined,
    faultDescription: undefined,
    repairMethod: 1,
    status: undefined,
  }
  formRef.value?.resetFields()
}

// 监听申请人变化，自动设置部门
watch(() => formData.value.applicantId, async (newApplicantId) => {
  if (newApplicantId) {
    // 查找选中的用户信息
    const selectedUser = userList.value.find(user => user.id === newApplicantId)
    if (selectedUser && selectedUser.deptId) {
      formData.value.departId = selectedUser.deptId
    }
  } else {
    // 如果清空了申请人，也清空部门选择
    formData.value.departId = undefined
  }
})


/** 获取当前用户信息 */
const getCurrentUser = async () => {
  try {
    const res = await getUserProfile()
    currentUser.value = res
    return res
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

</script>